import type { FridgeFreezerController, FridgeSettingGroup, LocalFlexSetting, LocalMode } from './definition'
import type { Remote } from '@/controller/base/types/remote'
import { useWorker, useRemote, wrapSafeActions } from '@/controller/base/index'
import { RemoteTypes } from '@/controller/base/remote'
import { createBaseState, BaseGetters, BaseActions, createBaseApplianceControl } from '../BaseAppliance'
import { defineStore } from 'pinia'
import {
  FLEX_KEY,
  FLEX_MODE_CUSTOM,
  FLEX_MODE_KEY,
  REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE,
  REFRIGERATION_ECO_MODE,
  REFRIGERATION_FRESH_MODE,
  REFRIGERATION_OFF_MODE,
  REFRIGERATION_VACATION_MODE,
  SETPOINT_TEMPERATURE_FREEZER,
  SETPOINT_TEMPERATURE_FREEZER2,
  SETPOINT_TEMPERATURE_REFRIGERATOR,
  SETPOINT_TEMPERATURE_REFRIGERATOR2,
  SETTING_ENABLECAMERAS,
  SMARTHYGIENE_ODORINDICATION_BAD,
  SMARTHYGIENE_ODORINDICATION_GOOD,
  SMART_HYGIENELITE_MODE,
  SMART_HYGIENE_CLOSED,
  SMART_HYGIENE_ENABLED,
  SMART_HYGIENE_MODE,
  SMART_HYGIENE_MODE_AUTO,
  SMART_HYGIENE_MODE_CLOSE,
  SMART_HYGIENE_NO_DISTURB,
  SMART_HYGIENE_QUALITY,
  SUPER_MODE_FREEZER,
  SUPER_MODE_FREEZER2,
  SUPER_MODE_REFRIGERATOR,
  SUPER_MODE_REFRIGERATOR2,
  SETTING_PRESET,
  WARMCOMPARTEMENT_ACTIVEPRESET,
  SETPOINT_TEMPERATURE_CHILLERLEFT,
} from '@/constants/Command'
import {
  getSetting,
  type ApplianceSetting,
  getFlexModeSetting,
  type ApplianceSettingConstraints,
  getStatusKey,
  getAllSetting,
} from '@/api/appliance'
import type { Response } from '@/utils/request'
import aesHelper from '@/utils/aesHelper'
import { useAuthStore } from '@/store/auth'
import store from '@/store'
import { useGlobalStore } from '@/store/global'
import { debounce } from 'lodash'

const authStore = useAuthStore()
const globalStore = useGlobalStore(store)

const isTemperatureSetting = (key: string) => key.indexOf('SetpointTemperature') !== -1
const getTemperatureSettingPrefix = (key: string) => key.replace(/^(\S+)\.SetpointTemperature$/, '$1')
const getChillerTemperatureSetting = (key: string) => key.replace(/^(\S+)Common\.SetpointTemperature$/, '$1')

const CustomSettingKeys = [SMART_HYGIENE_ENABLED, SETTING_ENABLECAMERAS]
const ModeSettingKeys = [REFRIGERATION_VACATION_MODE, REFRIGERATION_ECO_MODE, REFRIGERATION_FRESH_MODE]

export const FLEXMDOES = [
  {
    SIEMENS_name: '冷藏',
    BOSCH_name: '冷藏',
    key: 'Refrigeration.Common.EnumType.FoodPresets.Cool',
    value: '4',
    siemens_des: '适合作为普通冷藏空间使用。',
    bosch_des: '适合作为普通冷藏空间使用，扩大冷藏空间。',
  },
  {
    SIEMENS_name: '生鲜',
    BOSCH_name: '零度',
    key: 'Refrigeration.Common.EnumType.FoodPresets.Fresh',
    value: '0',
    siemens_des: '适合作为部分蔬果、奶制品等存储空间。',
    bosch_des: '适合作为果蔬保鲜的存储空间。',
  },
  {
    SIEMENS_name: '微冻',
    BOSCH_name: '冰鲜',
    key: 'Refrigeration.Common.EnumType.FoodPresets.LittleFreezing',
    value: '-4',
    siemens_des: '适合作为鱼肉类短期存储空间。',
    bosch_des: '适合作为肉类保鲜空间，无需解冻轻松切片。',
  },
  {
    SIEMENS_name: '深冻',
    BOSCH_name: '冷冻',
    key: 'Refrigeration.Common.EnumType.FoodPresets.DeepFreeze',
    value: '-18',
    siemens_des: '适合作为普通冷冻空间使用。',
    bosch_des: '适合作为普通冷冻空间使用，扩大冷冻空间。',
  },
  {
    SIEMENS_name: '酒饮',
    BOSCH_name: '暖鲜',
    key: 'Refrigeration.Common.EnumType.FoodPresets.Wine',
    value: '12',
    siemens_des: '适合作为部分葡萄酒等饮品存储空间。',
    bosch_des: '适合作为热带水果、巧克力、护肤品存储空间。',
  },
]

/**
 * 初始化数据
 */
export const createFridgeFreezerState: () => FridgeFreezerController.State = () => ({
  ...createBaseState(),
  /**
   * 当前显示的设置弹框数据
   */
  currentMenuGroupKey: '', // 当前显示弹框的设置Key
  currentMenuSettings: null, // 当前显示弹框的设置
  hasFlexCustom: {
    exist: false,
    active: false,
  }, // 是否有变温室自定义功能
  flexModes: [], // 百变储鲜室可选模式
  localMode: null, // 本地确认的变温模式
  localFlexModes: [], // 本地缓存的变温模式（包括确认和拒绝）
  showLocalFlexSetting: {
    newLocalFlexMode: {
      id: 0,
      temperature: 0,
      modelName: '',
      active: false,
      description: '',
    },
    temperature: 0,
    show: false,
    content: '',
    type: 0, // 0是新增，1是替换，2是过期或者不用设置
  }, // 是否提示变温活动更新
  flexModeId: '',
  flexModeName: '',
  smartHygieneQuality: '', // 活氧净空气等级
  isSmartHygieneLite: false, // 是否是smarthygienelite
  smartHygieneMode: '', // 活氧净模式
  smartHygieneLiteMode: '', // 活氧净lite模式
  isSmartHygieneNodisturb: false,
  isSuperModeFreezerCon: false, //速冻模式
  isSuperModeRefrigeratorCon: false, //速冷模式
  isNotDisturbMode: false, //勿扰模式
  isEnableCameras: false,
})
export const FridgeFreezerGetters: FridgeFreezerController.Getters = {
  ...BaseGetters,
  programGroupsConfig() {
    /**
     * 不使用程序分组功能
     *  - SMM类型
     */
    return null
  },

  isSmartHygiene() {
    return this._datasource.settings.some(({ key }) => key.includes('SmartHygiene'))
  },
  isNotDisturbModeCompunted() {
    return this._datasource.settings.some(({ key }) => key.includes('SuppressCriticalOdor'))
  },
  isEnableCamerasFnc() {
    return this._datasource.settings.some(({ key }) => key.includes('EnableCameras'))
  },
  isHasFlexTemp() {
    // 温度分组
    return this._datasource.settings.some(({ key }) => key.includes('FlexCompartment'))
  },
  isOdorIndication() {
    return this._datasource.status.some(({ key }) => key === SMART_HYGIENE_QUALITY)
  },

  settingGroups() {
    const brand = this._datasource.brand?.toUpperCase()
    let isSpecialtyZone = false
    let isSpecialtyZoneValue = ''
    const settingsGroup = this._datasource.settings.reduce<FridgeSettingGroup[]>((groups, rawSetting) => {
      const settingKey = rawSetting.key
      if (settingKey.includes(SETTING_PRESET)) {
        isSpecialtyZone = true
        isSpecialtyZoneValue = rawSetting.value as string
      }

      // 温度分组
      if (isTemperatureSetting(settingKey) || CustomSettingKeys.includes(settingKey)) {
        let name = rawSetting.name
        let value = rawSetting.value
        let unit = rawSetting.unit

        if ([FLEX_KEY, FLEX_MODE_KEY].includes(rawSetting.key)) {
          name = brand === 'SIEMENS' ? (this.isSmartHygieneLite ? '恒鲜杀菌系统' : '百变储鲜室') : '魔术变温空间'
        } else if ([REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE].includes(rawSetting.key)) {
          name = brand === 'SIEMENS' ? '零度生物保鲜室' : '零度维他保鲜室'
        } else if ([SETPOINT_TEMPERATURE_FREEZER, SETPOINT_TEMPERATURE_FREEZER2].includes(rawSetting.key)) {
          value = this.isSuperModeFreezerCon ? '速冻' : value
          unit = this.isSuperModeFreezerCon ? '' : unit
        } else if ([SETPOINT_TEMPERATURE_REFRIGERATOR, SETPOINT_TEMPERATURE_REFRIGERATOR2].includes(rawSetting.key)) {
          value = this.isSuperModeRefrigeratorCon ? '速冷' : value
          unit = this.isSuperModeRefrigeratorCon ? '' : unit
        } else if ([SMART_HYGIENE_ENABLED].includes(rawSetting.key)) {
          name = brand === 'SIEMENS' ? '智感恒鲜杀菌' : '活氧净'
          if (!this.isSmartHygieneLite && this.smartHygieneQuality) {
            if (this.smartHygieneQuality === SMARTHYGIENE_ODORINDICATION_GOOD) {
              value = '清新'
            } else if (this.smartHygieneQuality === SMARTHYGIENE_ODORINDICATION_BAD) {
              value = '一般'
            } else {
              value = '差'
            }
          } else {
            value = ''
          }
        } else if ([SETTING_ENABLECAMERAS].includes(rawSetting.key)) {
          if (rawSetting.value) {
            value = ''
            name = '冷藏室图像'
          } else {
            value = '暂未开启'
          }
        } else if ([SETPOINT_TEMPERATURE_CHILLERLEFT].includes(rawSetting.key)) {
          name = '保鲜抽屉左侧'
        } else if ([SETPOINT_TEMPERATURE_CHILLERLEFT].includes(rawSetting.key)) {
        }

        groups.push({
          name,
          key: rawSetting.key,
          value,
          raw: rawSetting,
          unit,
        })
      }

      return groups
    }, [])
    // isSpecialtyZone 特殊添加
    if (isSpecialtyZone) {
      let SpecialtyZoneValue = this._datasource.settings.find(
        (item) => item.key === WARMCOMPARTEMENT_ACTIVEPRESET
      ) as ApplianceSetting
      let index = SpecialtyZoneValue.value as string

      let arr = index.split('.')
      index = arr[arr.length - 1] + '.Name'
      let value = (this._datasource.settings.find((items) => items?.key.includes(index)) as ApplianceSetting)
        .displayvalue

      settingsGroup.push({
        name: brand === 'SIEMENS' ? '纯鲜臻品室' : '百变空间',
        key: SETTING_PRESET,
        value: value,
        raw: null,
        unit: '',
      })
    }
    const modeItem: FridgeSettingGroup[] = []
    const hasMode = this._datasource.settings.find((item) => ModeSettingKeys.includes(item.key))
    if (!hasMode) return settingsGroup
    modeItem.push({
      name: '模式选择',
      key: 'ModeChoose',
      value: '',
      raw: null,
    })

    this._datasource.settings.forEach((rawSetting) => {
      const settingKey = rawSetting.key
      // 温度分组
      if (ModeSettingKeys.includes(settingKey) && rawSetting.value) {
        modeItem[0].value += rawSetting.name as string
      }
    })
    if (!modeItem[0].value) modeItem[0].value = '关'

    return settingsGroup.concat(modeItem)
  },
  currentSettingGroup() {
    return this.settingGroups.find((group) => group.key === this.currentMenuGroupKey) || null
  },
  customIgnoredNoticeQueryKeys() {
    return ['Compartment.']
  },
}
export const FridgeFreezerActions: FridgeFreezerController.Actions = wrapSafeActions<
  FridgeFreezerController.Store,
  FridgeFreezerController.Actions
>({
  ...BaseActions,
  async loadMenuSettings(groupKey: string) {
    this.currentMenuGroupKey = groupKey

    // 自定义不加载菜单设置
    // if (CustomSettingKeys.includes(groupKey)) return
    const haId = this._datasource.haId
    if (isTemperatureSetting(groupKey)) {
      let itemsKeyPrefix = ''
      let itemsKey: string[] = []
      let flag = false
      if (groupKey === REFRIGERATION_CHILLER_COMMON_SETPOINT_TEMPERATURE) {
        itemsKeyPrefix = getChillerTemperatureSetting(groupKey)
      } else if (groupKey === SETPOINT_TEMPERATURE_FREEZER) {
        flag = true
        itemsKey = [SETPOINT_TEMPERATURE_FREEZER, SUPER_MODE_FREEZER]
      } else if (groupKey === SETPOINT_TEMPERATURE_REFRIGERATOR) {
        flag = true
        itemsKey = [SETPOINT_TEMPERATURE_REFRIGERATOR, SUPER_MODE_REFRIGERATOR]
      } else {
        itemsKeyPrefix = getTemperatureSettingPrefix(groupKey)
      }
      const fetchSettingTasks = this._datasource.settings.reduce<Promise<Response<ApplianceSetting>>[]>(
        (keys, { key }) => {
          if (flag) {
            if (itemsKey.includes(key)) {
              keys.push(getSetting(haId, key))
            }
          } else {
            if (key.startsWith(itemsKeyPrefix)) {
              keys.push(getSetting(haId, key))
            }
          }
          return keys
        },
        []
      )
      const results = await Promise.all(fetchSettingTasks)
      const settings = results.map((res) => res.data)
      this.currentMenuSettings = settings
    } else if (groupKey === 'ModeChoose') {
      const fetchSettingTasks = this._datasource.settings.reduce<Promise<Response<ApplianceSetting>>[]>(
        (keys, { key }) => {
          if (ModeSettingKeys.includes(key)) {
            keys.unshift(getSetting(haId, key))
          }
          return keys
        },
        []
      )
      const results = await Promise.all(fetchSettingTasks)
      const settings = results.map((res) => res.data)
      const isHasMode = settings.find((item) => item.value)
      settings.unshift({
        key: REFRIGERATION_OFF_MODE,
        mediumDescription: '',
        name: '关',
        type: 'Boolean',
        value: !isHasMode,
      })
      this.currentMenuSettings = settings
    } else if (groupKey === SETTING_PRESET) {
      const results = await getAllSetting(haId)
      const settings = results.data.settings
      const ActivePreset = settings.find((items) => items.key === WARMCOMPARTEMENT_ACTIVEPRESET)
      const nameArry: ApplianceSetting[] = []
      const usedArry: ApplianceSetting[] = []
      const presetData: ApplianceSetting[] = []
      settings.map((items) => {
        if (items.key.includes(SETTING_PRESET)) {
          if (items.key.endsWith('.Name')) {
            nameArry.push(items)
          } else {
            usedArry.push(items)
          }
        }
      })
      usedArry.map((items) => {
        items.useKey = items.key.replace('.Used', '')
      })
      nameArry.map((items) => {
        usedArry.map((groups) => {
          if (items.key.includes(groups.useKey)) {
            items.statusValue = groups.value
            items.statusKey = groups.key
            items.type = 'present'
            items.useKey = groups.useKey

            if (items.key.replace('.Setting', '.SettingList').includes(ActivePreset?.value as string)) {
              items.activePreset = true
            } else {
              items.activePreset = false
            }
            presetData.push(items)
          }
        })
      })
      this.currentMenuSettings = presetData
    } else {
      const result = await getSetting(haId, groupKey)
      const settings = result.data
      this.currentMenuSettings = [settings]
    }
  },
  /**
   * 初始化百变储鲜室模式
   */
  async initFlexMode() {
    const res = await getSetting(this._datasource.haId, FLEX_MODE_KEY)
    if (res.code == 0) {
      let tempArr = res.data.constraints as ApplianceSettingConstraints
      let flexModes = []
      if (Array.isArray(tempArr.allowedvalues)) {
        for (let i = 0; i < tempArr.allowedvalues.length; i++) {
          if (tempArr.allowedvalues[i] == FLEX_MODE_CUSTOM) {
            this.hasFlexCustom.exist = true
            this.hasFlexCustom.active = res.data.value === FLEX_MODE_CUSTOM
          }
          for (let j = 0; j < FLEXMDOES.length; j++) {
            if (tempArr.allowedvalues[i] == FLEXMDOES[j].key) {
              flexModes.push(FLEXMDOES[j])
              break
            }
          }
        }
      }
      this.flexModes = flexModes
      if (this.hasFlexCustom.exist) {
        this.getFlexCustomPush(res.data.value, '')
      }
    }
  },
  async getFlexCustomPush(flexMode: { value: any; name: string }, flexValue: any) {
    this.localFlexModes = uni.getStorageSync('fridgeFlexModes') // 本地节日温度缓存
    if (!this.localFlexModes) this.localFlexModes = []
    let userId = aesHelper.decrypt(authStore.ciamId, authStore.key, authStore.iv)
    let localModes: string | any[] = []
    for (let i = 0; i < this.localFlexModes.length; i++) {
      if (this.localFlexModes[i].userId == userId && this._datasource.haId == this.localFlexModes[i].haId) {
        localModes = this.localFlexModes[i].value // 当前用户家电设置过的节日温度（包括忽略）
        for (let j = 0; j < localModes.length; j++) {
          if (localModes[j].active) {
            this.localMode = localModes[j] // 当前用户家电设置过的节日温度确认设置过（非忽略）
          }
          break
        }
      }
    }
    let res = await getFlexModeSetting(this._datasource.haId)
    if (res.data) {
      if (this.flexModeId) {
        // 从通知跳转过来
        if (this.flexModeId == res.data.id) {
          // 活动未过期
          let hasSameMode = false
          for (let i = 0; i < localModes.length; i++) {
            if (localModes[i] && localModes[i].active && localModes[i].id == res.data.id) {
              // 模式已设置
              this.showLocalFlexSetting = {
                newLocalFlexMode: res.data,
                show: true,
                content: 'FridgeFreezer.FlexCompartment.Exist.Text',
                type: 2,
              }
              hasSameMode = true
              break
            }
          }
          if (!hasSameMode) {
            // 模式未设置
            this.showLocalFlexSetting = {
              newLocalFlexMode: res.data,
              show: true,
              content: res.data.modelName as string,
              type: this.localMode ? 1 : 0,
            }
          }
        } else if (this.flexModeId != res.data.id) {
          // 模式已过期
          this.showLocalFlexSetting = {
            newLocalFlexMode: res.data,
            show: true,
            content: 'FridgeFreezer.FlexCompartment.Expired.Text',
            type: 2,
          }
        }
      } else {
        // 家电列表页打开
        let hasSameMode = false
        for (let i = 0; i < localModes.length; i++) {
          if (localModes[i] && localModes[i].id == res.data.id) {
            hasSameMode = true
            break
          }
        }
        if (!hasSameMode) {
          this.showLocalFlexSetting = {
            newLocalFlexMode: res.data,
            show: true,
            content: res.data.modelName as string,
            type: this.localMode ? 1 : 0,
          }
        }
      }
    }

    if (this.flexModeId && !res.data) {
      //模式已过期
      this.showLocalFlexSetting = {
        newLocalFlexMode: {
          modelName: this.flexModeName,
          id: this.flexModeId,
          temperature: 0,
          active: false,
          description: '',
        },
        show: true,
        content: 'FridgeFreezer.FlexCompartment.Expired.Text',
        type: 2,
      }
    }
  },
  updateFlexModalContent(content: LocalFlexSetting) {
    this.showLocalFlexSetting = content
  },
  updateLocalMode(localMode: LocalMode) {
    this.localMode = localMode
  },
  /**
   * 获取活氧净是否是lite
   */
  getStatusLite() {
    getStatusKey(this._datasource.haId, SMART_HYGIENE_QUALITY).then(
      (res) => {
        this.smartHygieneQuality = res.data.value as string
        this.isSmartHygieneLite = false
      },
      (error) => {
        this.isSmartHygieneLite = true
      }
    )
  },
})
export const FridgeFreezerObserve: Remote.Observe<FridgeFreezerController.Store> = {}
export const FridgeFreezerBatchObserves: Remote.BatchObserve<FridgeFreezerController.Store>[] = [
  {
    matcher: () => true,
    handler: debounce((_, remote) => {
      remote.loadAllSetting()
      if (remote.store.currentMenuGroupKey) {
        remote.store.loadMenuSettings(remote.store.currentMenuGroupKey)
      }
    }, 500),
  },
]

/**
 * 组合API
 */
const useStore = defineStore<
  'FridgeFreezer',
  FridgeFreezerController.State,
  FridgeFreezerController.Getters,
  FridgeFreezerController.Actions
>('FridgeFreezer', {
  state: createFridgeFreezerState,
  getters: FridgeFreezerGetters,
  actions: FridgeFreezerActions,
})

// 组件使用
export function useFridgeFreezerControl(): FridgeFreezerController.Control {
  const store = useStore() as FridgeFreezerController.Store
  const worker = useWorker(store)
  const remote = useRemote(store)
  return { store, worker, remote }
}

// 页面使用
export function createFridgeFreezerControl(
  control: FridgeFreezerController.Control = useFridgeFreezerControl()
): FridgeFreezerController.Control {
  const { store, worker, remote } = control

  createBaseApplianceControl(control, { remoteType: RemoteTypes.Inhouse })

  worker.onLoad(async () => {
    await Promise.all([
      // 加载状态
      remote.loadAllStatus(),
      remote.loadAllSetting(),
    ])
    if (store.isHasFlexTemp) {
      store.initFlexMode()
    }
    if (store.isSmartHygiene) {
      if (store.isOdorIndication) {
        store.getStatusLite()
      } else {
        store.isSmartHygieneLite = true
      }

      // await remote.loadSupportCommands()
    }

    if (store.isNotDisturbModeCompunted) {
      store.isNotDisturbMode = true
    }
    if (store.isEnableCamerasFnc) {
      let isfnc = store._datasource.settings.find((items) => items.key === SETTING_ENABLECAMERAS)
      if (isfnc?.value) {
        store.isEnableCameras = true
      } else {
        store.isEnableCameras = false
      }
    }

    // await store.loadAvailableParameter()
  })
  remote.addObserve(FridgeFreezerObserve)
  remote.addBatchObserves(FridgeFreezerBatchObserves)

  useFridgeEffects(control)

  return control
}

function useFridgeEffects(control: FridgeFreezerController.Control) {
  useFridgeFreezerBinding(control)
}

function useFridgeFreezerBinding(control: FridgeFreezerController.Control) {
  const { worker } = control

  worker.useGetValueBinding('smartHygieneMode', {
    key: SMART_HYGIENE_MODE,
    from: 'status',
  })
  worker.useGetValueBinding('smartHygieneLiteMode', {
    key: SMART_HYGIENELITE_MODE,
    from: 'status',
  })
  worker.useGetValueBinding('isSmartHygieneNodisturb', {
    key: SMART_HYGIENE_NO_DISTURB,
    from: 'setting',
  })
  worker.useGetValueBinding('isSuperModeFreezerCon', {
    key: SUPER_MODE_FREEZER,
    from: 'setting',
  })
  worker.useGetValueBinding('isSuperModeFreezerCon', {
    key: SUPER_MODE_FREEZER2,
    from: 'setting',
  })
  worker.useGetValueBinding('isSuperModeRefrigeratorCon', {
    key: SUPER_MODE_REFRIGERATOR,
    from: 'setting',
  })
  worker.useGetValueBinding('isSuperModeRefrigeratorCon', {
    key: SUPER_MODE_REFRIGERATOR2,
    from: 'setting',
  })
}
